package com.itheima.tliasmanagent.interceptor;

import com.itheima.tliasmanagent.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class TokenInteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求路径
        String url = request.getRequestURL().toString();
        //2. 判断是否是登录的请求 如果是 直接放行
        if(url.contains("login")){
            return true;
        }
        //3.从请求头中获取token
        String jwt = request.getHeader("token");
        //4. 判断token是否存在  不存在返回  401
        if(jwt == null || jwt.length() ==0){
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //5. 解析token 如果解析失败 返回401
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //6. 放行
       return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
